package com.tzy.newbank.AOPlog;

import com.tzy.newbank.Pojo.Banklog;
import com.tzy.newbank.mapper.BanklogMapper;
import com.tzy.newbank.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.LocalVariableTableParameterNameDiscoverer;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.time.LocalDateTime;

@Aspect
@Slf4j
@Component
public class myAOP {


    private final LocalVariableTableParameterNameDiscoverer parameterNameDiscoverer = new LocalVariableTableParameterNameDiscoverer();


    @Pointcut("@annotation(com.tzy.newbank.AOPlog.AOPTag)")
    private void myCut(){}

    @Autowired
    private BanklogMapper mapper;
    @Autowired
    private HttpServletRequest request;
    @Around("myCut()")
    public Object recordUseLog(ProceedingJoinPoint joinPoint)throws Throwable{
        log.info("AOP模块recordUseLog捕获到了执行方法："+joinPoint.getSignature());
        //获取jwt令牌中的用户名信息
        String jwt=request.getParameter("jwtToken");
        //String jwt =JwtUtils.jwt;
        Claims claims = JwtUtils.readJWT(jwt);
        String name = (String) claims.get("name");
        //方法名
        String method2= joinPoint.getSignature().getName();
        //时间
        LocalDateTime now = LocalDateTime.now();
        //返回值
        log.info("Aop拦截的方法开始执行");
        Object result = joinPoint.proceed();
        log.info("Aop拦截的方法执行完毕");

        //获取方法执行的具体细节。
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        String[] parameterNames = this.parameterNameDiscoverer.getParameterNames(method);
        for (int i = 0; i < parameterNames.length; i++) {
            log.info("{}: {}", parameterNames[i], joinPoint.getArgs()[i]);
        }
        log.info("返回结果: {}", result);

        Banklog uselog = new Banklog(name,method2,now);
        mapper.saveLog(uselog);
        log.info("AOP模块recordUseLog,完成方法的记录："+joinPoint.getSignature());
        return result;
    }

}
